const { stream } = require('exceljs')
const { MongooseDocument } = require('../../cfg/dbconfig.js')
var mongoose = require('../../cfg/dbconfig.js')
// title=test&uid=118&subject=1&grade=31&filename=share_record_20201108105854.mp4&desc=&cover=share_record_20201108105854.JPG
var vodSchema = new mongoose.Schema({
    title: {
        type: String,
        default: '未命名标题'
    },
    uid: {
        type: String,
        default: '未命名上传者'
    },
    subject: {
        type: String,
        default: '未注明学科'
    },
    grade: {
        type: String,
        default: '未注明年级'
    },
    filename: String,
    desc: {
        type: String,
        default: '未做描述'
    },
    cover: {
        type: String,
        default: 'nofrontimage.jpg'
    },
    creattime: {
        type: Date,
        default: Date.now()
    }
}, { collection: 'vod' }
)

vodSchema.statics.Save = async function (doc) {
    let obj = new this(doc)
    let res = await obj.save();
    return res;
}

//更新记录
vodSchema.statics.Update = async function (doc) {
    let id = doc._id;
    delete doc._id;
    let result = await this.updateOne({ _id: id }, doc).exec()
    return result
}
//删除记录
vodSchema.statics.Del = async function (id) {
    let result = await this.deleteOne({ _id: id }).exec()
    return result;
}

//分页查询

vodSchema.statics.myPaging = async function (keyword, pagesize, lastid) {
    keyword = keyword ? keyword : ''
    pagesize = pagesize ? parseInt(pagesize) : 12
    var query = {}
    let reco = []
    if (lastid) {
        query = {
            $or: [
                { 'title': { $regex: keyword } },
                { 'desc': { $regex: keyword } },
                { 'uid': { $regex: keyword } },
                { 'grade': { $regex: keyword } },
                { 'subject': { $regex: keyword } }
            ],
            _id: { $lt: lastid }
        }
    } else {
        query = {
            $or: [
                { 'title': { $regex: keyword } },
                { 'desc': { $regex: keyword } },
                { 'uid': { $regex: keyword } },
                { 'grade': { $regex: keyword } },
                { 'subject': { $regex: keyword } }
            ]
        }
    }

    let countQuery = {
        $or: [
            { 'title': { $regex: keyword } },
            { 'desc': { $regex: keyword } },
            { 'uid': { $regex: keyword } },
            { 'grade': { $regex: keyword } },
            { 'subject': { $regex: keyword } }
        ]
    }

    if (pagesize == -1) {
        reco = await this
            .find(query)
            .sort({ _id: -1 })
            .exec();
    } else {
        reco = await this
            .find(query)
            .sort({ _id: -1 })
            .limit(pagesize)
            .exec();
    }
    let count = await this.countDocuments(countQuery).exec();
    return { "recordset": reco, "count": count }
}

module.exports = mongoose.model('vod', vodSchema)
